// 引入宠物服务
const petService = require('../../services/pet');

Page({
  data: {
    petTypes: ['猫', '狗', '兔子', '鼠类', '鸟类', '其他'],
    formData: {
      name: '',
      type: undefined,
      breed: '',
      gender: 1,
      birthday: '',
      color: '',
      weight: '',
      sterilized: false,
      habits: '',
      avatarUrl: ''
    },
    today: '',
    tempFilePath: '' // 临时文件路径
  },

  onLoad: function() {
    // 设置今天日期为选择器结束日期
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const day = today.getDate();
    
    this.setData({
      today: `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
    });
  },
  
  // 宠物类型选择器变化
  bindTypeChange: function(e) {
    this.setData({
      'formData.type': parseInt(e.detail.value)
    });
  },
  
  // 性别单选框变化
  bindGenderChange: function(e) {
    this.setData({
      'formData.gender': parseInt(e.detail.value)
    });
  },
  
  // 出生日期选择器变化
  bindBirthdayChange: function(e) {
    this.setData({
      'formData.birthday': e.detail.value
    });
  },
  
  // 是否绝育开关变化
  bindSterilizedChange: function(e) {
    this.setData({
      'formData.sterilized': e.detail.value
    });
  },
  
  // 选择图片
  chooseImage: function() {
    const that = this;
    
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        // 设置临时文件路径和预览图
        that.setData({
          tempFilePath: res.tempFilePaths[0],
          'formData.avatarUrl': res.tempFilePaths[0]
        });
      }
    });
  },
  
  // 上传图片
  uploadImage: function() {
    if (!this.data.tempFilePath) {
      return Promise.resolve('');
    }
    
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '上传图片中...',
      });
      
      const token = wx.getStorageSync('token');
      
      wx.uploadFile({
        url: getApp().globalData.baseUrl + '/file/upload',
        filePath: this.data.tempFilePath,
        name: 'file',
        header: {
          Authorization: token
        },
        formData: {
          type: 'pet'
        },
        success: function(res) {
          wx.hideLoading();
          const data = JSON.parse(res.data);
          
          if (data.code === 200) {
            resolve(data.data);
          } else {
            reject(new Error(data.message || '上传图片失败'));
          }
        },
        fail: function(err) {
          wx.hideLoading();
          reject(err);
        }
      });
    });
  },
  
  // 表单提交
  submitForm: function(e) {
    const formData = e.detail.value;
    
    // 表单验证
    if (!formData.name) {
      wx.showToast({
        title: '请输入宠物名称',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.formData.type === undefined) {
      wx.showToast({
        title: '请选择宠物类型',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.breed) {
      wx.showToast({
        title: '请输入宠物品种',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.gender) {
      wx.showToast({
        title: '请选择宠物性别',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.birthday) {
      wx.showToast({
        title: '请选择出生日期',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载中
    wx.showLoading({
      title: '保存中...',
      mask: true
    });
    
    // 先上传图片，再提交表单
    this.uploadImage().then(avatarUrl => {
      // 构建提交的数据
      const petData = {
        name: formData.name,
        type: this.data.formData.type,
        breed: formData.breed,
        gender: parseInt(formData.gender),
        birthday: formData.birthday,
        color: formData.color || '',
        weight: formData.weight ? parseFloat(formData.weight) : null,
        sterilized: formData.sterilized || false,
        habits: formData.habits || '',
        photo: avatarUrl || ''
      };
      
      // 调用添加宠物API
      return petService.addPet(petData);
    }).then(res => {
      wx.hideLoading();
      
      wx.showToast({
        title: '添加成功',
        icon: 'success',
        duration: 2000,
        success: function() {
          // 返回宠物列表页
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        }
      });
    }).catch(err => {
      console.error('添加宠物失败', err);
      wx.hideLoading();
      
      wx.showToast({
        title: err.message || '添加失败，请重试',
        icon: 'none'
      });
    });
  }
}); 